var { sequelize } = require("../lib/db");
var common = require("../lib/common");
var articlecategory = sequelize.import("../models/articlecategory");

exports.getList = function(req, res,next) {

  let page = parseInt(req.query.page || 1); //页码（默认第1页）
  let limit = parseInt(req.query.limit || 10); //每页显示条数（默认10条）
  let name = "%"+req.query.name+"%" || ''; //图书名称
  let total = 0;

  articlecategory.findAndCountAll({
    where:{$or:[{categoryname:{$like:name}},{createtime:{$like:name}}]},
    offset:(page - 1) * limit,//开始的数据索引，比如当page=2 时offset=10 ，而pagesize我们定义为10，则现在为索引为10，也就是从第11条开始返回数据条目
    limit:limit//每页限制返回的数据条数
  }).then(function(list){
    res.json(list);
  });

}

exports.delete = function(req,res){
  let id = req.params.id || '';
  if (!id) {
    return res.json({"errcode": 40002, "errmsg": "不合法的参数"});
  }

  articlecategory.destroy({
    where: {
        id: id
    }
  }).then(function(msg){
      res.json({"errcode": 0, "errmsg": "删除成功"});
  });

}


exports.removeBatch = function(req,res){
  let ids = req.params.ids;
  ids = ids.split(',');

  // sequelize.transaction(function(t){

  //   return articlecategory.destroy({
  //     where: {
  //         id: id
  //     }
  //   }),{transaction: t}.then(function(msg){
  //       res.json({"errcode": 0, "errmsg": "删除成功"});
  //   });

  // });

  ids.forEach(element => {
    articlecategory.destroy({
      where: {
          id: element
      }
    }).then(function(msg){
        
    });
  });
  res.json({"errcode": 0, "errmsg": "删除成功"});
}

exports.add = function(req,res){
  let categoryname = req.body.categoryname;
  articlecategory.create({
    categoryname:categoryname
  }).then(function(msg){
    res.json({"errcode": 0, "errmsg": "添加成功"});
  });
}

exports.update = function(req,res){
  let categoryname = req.body.categoryname;
  articlecategory.update({categoryname:categoryname}, {
    where: {
        id: req.body.id
    }
  }).then(function(msg){
    return res.json({"errcode": 0, "errmsg": "修改成功"});
  });
  
}

exports.getFindId = function(req,res){
  let id = req.params.id || "";
  res.json(articlecategory.findById(id));
}
